/**
 * Copyright [2019] [LiBo/Alex of copyright liboware@gmail.com ]
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.cloud.base.util.expression;
import fr.expression4j.basic.MathematicalElement;
import fr.expression4j.basic.OperatorManager;
import fr.expression4j.core.Catalog;
import fr.expression4j.core.Expression;
import fr.expression4j.core.Parameters;
import fr.expression4j.core.exception.EvalException;
import fr.expression4j.core.exception.ParametersException;
import fr.expression4j.core.exception.ParsingException;
import fr.expression4j.core.predefine.AbstractFunction;
import fr.expression4j.factory.ExpressionFactory;
import fr.expression4j.factory.NumberFactory;
import fr.expression4j.util.ParameterUtil;

import java.util.List;

/**
 * @project-name:standard-cloud
 * @package-name:com.hyts.cloud.base.util.expression
 * @author:LiBo/Alex
 * @create-date:2020-06-29 21:49
 * @copyright:libo-alex4java
 * @email:liboware@gmail.com
 * @description:
 */
public class TestUserDefine {

    /**
     * @param args
     */
    public static void main(String[] args) {
        try {
            Catalog catalog = ExpressionFactory.getCatalog();
            catalog.addExpression(new MyFun());
            Expression exp = ExpressionFactory.createExpression("f()=abcd(13)");
            double val = exp.evaluate(null).getRealValue();
            System.out.println("result:" + val);
        } catch (ParsingException e) {
            e.printStackTrace();
        } catch (EvalException e) {
            e.printStackTrace();
        }
    }

}

class MyFun extends AbstractFunction {

    @Override
    public MathematicalElement evaluate(Parameters arg0) throws EvalException {
        try {
            double d = arg0.getParameter("x").getRealValue();//似乎只能是x一个
            return NumberFactory.createReal(d + 1);
        } catch (ParametersException e) {
            throw new EvalException("error");
        }
    }

    @Override
    public MathematicalElement evaluate(OperatorManager arg0, Parameters arg1) throws EvalException {
        return evaluate(arg1);
    }

    @Override
    public Catalog getCatalog() {
        return ExpressionFactory.getCatalog();
    }

    @Override
    public String getName() {
        return "abcd";//方法名
    }

    @Override
    public List getParameters() {
        return ParameterUtil.generateXParameters();
    }
}
